<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas 水印示例</title>
    <style>
        canvas {
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
<input type="file" id="upload" accept="image/*" />
<canvas id="canvas"></canvas>
<button id="saveBtn">保存图片</button>

<script>
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    // 处理上传的图片
    document.getElementById('upload').addEventListener('change', (event) => {
        const file = event.target.files[0];
        const reader = new FileReader();

        reader.onload = (e) => {
            const img = new Image();
            img.onload = () => {
                // 设置画布大小
                canvas.width = img.width;
                canvas.height = img.height;

                // 绘制原始图片
                ctx.drawImage(img, 0, 0);

                // 根据图片大小设置水印属性
                const watermarkOptions = calculateWatermarkOptions(img.width, img.height);
                addWatermark("水印文本", 45, watermarkOptions.fontSize, watermarkOptions.horizontalSpacing, watermarkOptions.verticalSpacing);
            };
            img.src = e.target.result;
        };

        if (file) {
            reader.readAsDataURL(file);
        }
    });

    // 计算水印字体大小和间距
    function calculateWatermarkOptions(width, height) {
        const baseFontSize = Math.min(width, height) / 55; // 将基准字体大小设置为图片最小边的1/40
        const horizontalSpacing = Math.max(width / 20, 40); // 水平方向间距，设定为宽度的1/20
        const verticalSpacing = Math.max(height / 15, 20); // 垂直方向间距，设定为高度的1/20

        return {
            fontSize: baseFontSize,
            horizontalSpacing: horizontalSpacing,
            verticalSpacing: verticalSpacing
        };
    }

    // 添加水印
    function addWatermark(text, angle, fontSize, horizontalSpacing, verticalSpacing) {
        ctx.save(); // 保存当前状态
        ctx.fillStyle = 'rgba(255, 255, 255, 0.5)'; // 设置水印颜色
        ctx.font = `${fontSize}px KaiTi`; // 设置动态字体和大小
        ctx.textAlign = 'center'; // 文本居中对齐

        // 绘制水印文本
        for (let y = 0; y < canvas.height; y += verticalSpacing) {
            for (let x = 0; x < canvas.width; x += horizontalSpacing) {
                ctx.save(); // 保存当前状态
                ctx.translate(x, y); // 移动到指定位置
                ctx.rotate(angle * Math.PI / 180); // 旋转文本
                ctx.fillText(text, 0, 0); // 在新的位置绘制文本
                ctx.restore(); // 恢复状态
            }
        }

        ctx.restore(); // 恢复状态
    }

    // 保存图片
    document.getElementById('saveBtn').addEventListener('click', () => {
        const link = document.createElement('a');
        link.href = canvas.toDataURL('image/png'); // 获取图像数据URL
        link.download = 'watermarked-image.png'; // 设置下载的文件名
        link.click(); // 触发下载
    });
</script>
</body>
</html>
